<template>
  <div class="app-container">
    <el-dialog :close-on-click-modal="false" :visible.sync="open" width="1300px" :title="title" append-to-body>
      <el-form ref="shipmentForm" :model="shipmentForm" :rules="rules" label-width="100px">
        <el-divider content-position="left">运单信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="运单编号" prop="code">
              <el-input v-model="shipmentForm.code" placeholder="系统自动生成" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运单日期" prop="time">
              <el-date-picker clearable
                              v-model="shipmentForm.time"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择运单日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运输协议号" prop="tan">
              <el-input v-model="shipmentForm.tan" placeholder="请输入运输协议号"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运作模式" prop="operationPattern">
              <el-select clearable v-model="shipmentForm.operationPattern" placeholder="请选择运作模式"
                         style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.OperationPattern"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="承运商" prop="jcCarrierId">
              <el-select clearable v-model="shipmentForm.jcCarrierId" placeholder="请选择承运商">
                <el-option v-for="carrier in carrierList" :key="carrier.id" :label="carrier.name"
                           :value="carrier.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车型" prop="jcVehicleId">
              <el-select clearable v-model="shipmentForm.jcVehicleId" placeholder="请选择车型" @change="changeVehicle">
                <el-option v-for="vehicle in vehicleTypes" :key="vehicle.id" :label="vehicle.code" :value="vehicle.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="回单份数" prop="backNumber">
              <el-input-number v-model="shipmentForm.backNumber" placeholder="请输入回单份数"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运输方式" prop="shipmentMethod">
              <el-select clearable v-model="shipmentForm.shipmentMethod" placeholder="请选择运输方式">
                <el-option v-for="dict in dict.type.TransportMenth" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="要求发运日期" prop="planLeaveTime">
              <el-date-picker clearable
                              v-model="shipmentForm.planLeaveTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择要求发运日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="要求到车日期" prop="requireArriveTime">
              <el-date-picker clearable
                              v-model="shipmentForm.requireArriveTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择要求到车日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款方式" prop="feeType">
              <el-select clearable v-model="shipmentForm.feeType" placeholder="请选择付款方式">
                <el-option v-for="dict in dict.type.Clearing" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际发车日期" prop="factLeaveTime">
              <el-date-picker clearable v-model="shipmentForm.factLeaveTime" type="date" value-format="yyyy-MM-dd"
                              placeholder="实际发车日期" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际到车日期" prop="factArriveTime">
              <el-date-picker clearable v-model="shipmentForm.factArriveTime" type="date" value-format="yyyy-MM-dd"
                              placeholder="实际到车日期" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="车牌号" prop="license">
              <el-select clearable v-model="shipmentForm.license" placeholder="请选择车牌号"
                         @change="handleLicenseSelect">
                <el-option v-for="dict in licenseList" :key="dict.id" :label="dict.code" value-key="value"
                           :value="dict.code"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机名称" prop="outDriver">
<!--              <el-select v-model="shipmentForm.outDriver" filterable clearable remote reserve-keyword placeholder="请输入关键词" :remote-method="queryDriverSearch" :loading="loading">-->
<!--                <el-option v-for="item in driverList" :key="item.userId" :label="item.dept.deptName + '-'+ item.nickName" :value="item.userId" />-->
<!--              </el-select>-->
              <el-autocomplete v-model="shipmentForm.outDriver" :fetch-suggestions="queryDriverSearch" placeholder="请输入司机名称进行搜索" @select="handleDriverSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机电话" prop="outPhone">
              <el-input v-model="shipmentForm.outPhone" placeholder="请输入司机电话"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">站点信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="起运站" prop="jcFromOrganizationId">
              <el-select clearable filterable v-model="shipmentForm.jcFromOrganizationId" placeholder="请选择起运站" @change="changeOrg" readonly="readonly">
                <el-option v-for="dict in orgList" :key="dict.id" :label="dict.name" :value="dict.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目的站" prop="jcToOrganizationId">
              <el-select clearable filterable v-model="shipmentForm.jcToOrganizationId" placeholder="请选择目的站" @change="changeOrg" readonly="readonly">
                <el-option v-for="dict in orgList" :key="dict.id" :label="dict.name" :value="dict.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="经由站" prop="orgIds">
              <el-select clearable filterable v-model="shipmentForm.orgIdsArray" placeholder="请选择经由站" multiple style="width: 100%;"
                         @change="$forceUpdate()" readonly="readonly">
                <el-option v-for="dict in viaOrgIds" :key="dict.id" :label="dict.name" :value="dict.id + ''"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">备注</el-divider>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input type="textarea" v-model="shipmentForm.description" placeholder="请输入备注"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常原因" prop="abnormal">
              <el-input type="textarea" v-model="shipmentForm.abnormal" placeholder="请输入异常原因"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <el-divider content-position="left">台帐明细信息</el-divider>
      <el-row :gutter="10" class="mb8" v-if="shipmentForm.status == null || shipmentForm.status === 1">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddJcLedgerDetail">添加
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteJcLedgerDetail">删除
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="ledgerDetails" :row-class-name="rowJcLedgerDetailIndex"
                @selection-change="handleJcLedgerDetailSelectionChange" ref="jcLedgerDetail">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="承运商" prop="jcCarrierId" width="150">
          <template #default="scope">
            <el-select clearable v-model="scope.row.jcCarrierId" placeholder="请选择承运商">
              <el-option v-for="carrier in carrierList" :key="carrier.id" :label="carrier.name"
                         :value="carrier.id"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="费用类型" prop="name">
          <template #default="scope">
            <el-select clearable v-model="scope.row.jcFeeTypeId" placeholder="请选择费用类型" size="mini">
              <el-option v-for="dict in feeTypeData" :key="dict.id" :label="dict.name" :value="dict.id"
                         @change="changeFeeType(scope.row,dict)"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="amount">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.amount" placeholder="请输入金额"
                      @input="changeAmount(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="税率" prop="taxrate">
          <template #default="scope">
            <el-select clearable v-model="scope.row.taxrate" placeholder="请选择税率">
              <el-option v-for="dict in dict.type.TaxRate" :key="dict.value" :label="dict.label"
                         :value="Number(dict.label)"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="税金" prop="input">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.input" placeholder="请输入税金" readonly="readonly"/>
          </template>
        </el-table-column>
        <el-table-column label="成本" prop="outcome">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.outcome" placeholder="请输入成本" readonly="readonly"/>
          </template>
        </el-table-column>
        <el-table-column label="收款方式" prop="collectMethod">
          <template #default="scope">
            <el-select v-model="scope.row.collectMethod" placeholder="请选择收款方式">
              <el-option v-for="dict in dict.type.CollectMethod" :key="dict.value" :label="dict.label"
                         :value="dict.value"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="结算方式" prop="settlementMethod">
          <template #default="scope">
            <el-select v-model="scope.row.settlementMethod" placeholder="请选择结算方式">
              <el-option v-for="dict in dict.type.Clearing" :key="dict.value" :label="dict.label"
                         :value="dict.value"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="description">
          <template #default="scope">
            <el-input v-model="scope.row.description" placeholder="请输入备注"/>
          </template>
        </el-table-column>
      </el-table>
      <!--  靠右-->
      <div style="display: flex;justify-content: center;margin-top: 15px;">
        <el-button type="primary" @click="submitShipmentFormForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {getShipment, saveAbnormalShipment} from "@/api/shipment/shipment";
import {allListCarrier} from "@/api/vehicle/carrier";
import {allListVehicle} from "@/api/vehicle/vehicle";
import {orgTree} from "@/api/kysys/sysOrganization";
import {listFeeTypeOption} from "@/api/fee/feeType";
import {searchVehicleExistList} from "@/api/vehicle/vehicleHead";
import {searchListDriver} from "@/api/vehicle/driver";

export default {
  name: "ShipmentForm",
  dicts: ['CommDataStatus', 'CarrierType', 'OperationPattern', 'TransportMenth', 'Clearing', 'CollectMethod', 'TaxRate', 'Direction'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 台帐明细表格数据
      ledgerDetails: [],
      checkedJcLedgerDetail: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      shipmentForm: {},
      // 表单校验
      rules: {
        license: [
          {required: true, message: "车牌号不能为空", trigger: "blur"}
        ],
        operationPattern: [
          {required: true, message: "运作模式不能为空", trigger: "blur"}
        ],
        outDriver: [
          {required: true, message: "司机名称不能为空", trigger: "blur"}
        ],
        time: [
          {required: true, message: "运单日期不能为空", trigger: "blur"}
        ],
        jcDriverId: [
          {required: true, message: "司机不能为空", trigger: "change"}
        ],
        jcVehicleId: [
          {required: true, message: "车型不能为空", trigger: "change"}
        ],
        jcFromOrganizationId: [
          {required: true, message: "起运站不能为空", trigger: "change"}
        ],
        jcToOrganizationId: [
          {required: true, message: "目的站不能为空", trigger: "change"}
        ],
        outPhone: [
          {required: true, message: "司机电话不能为空", trigger: "blur"}
        ],
        abnormal: [
          {required: true, message: "异常原因不能为空", trigger: "blur"}
        ],
      },
      carrierList: [],
      licenseList: [],
      driverList: [],
      vehicleTypes: [],
      orgList: [],
      // 经由站组织机构集合
      viaOrgIds: [],
      feeTypeData: [],
      zoom: 12,
      center: [102.829208, 24.852349],
      mapPosData: {},
    }
  },
  created() {
    this.getAllCarrier();
    this.getAllVehicle();
    this.getOrgList();
    this.getFeeTypeData();
  },
  methods: {
    getAllCarrier() {
      allListCarrier().then(response => {
        this.carrierList = response.data;
      });
    },
    getAllVehicle() {
      allListVehicle().then(response => {
        this.vehicleTypes = response.data;
      });
    },
    /** 车牌号搜索 */
    changeVehicle(val) {
      this.licenseList = [];
      debugger
      searchVehicleExistList(val).then(response => {
        this.licenseList = response.data;
      });
    },
    /** 车牌号选中 */
    handleLicenseSelect(val) {
      this.shipmentForm.license = val;
      this.licenseList.forEach(item => {
        if (item.code === val) {
          this.shipmentForm.jcVehicleHeadId = item.id;
          this.shipmentForm.outDriver = item.driver;
          this.shipmentForm.jcDriverId = item.jcDriverId;
          this.shipmentForm.outPhone = item.iphone;
        }
      });
    },
    /** 司机名称搜索 */
    queryDriverSearch(query, cb) {
      this.driverList = [];
      if (query && query !== "" && query.length >= 2) {
        searchListDriver(query).then(response => {
          // 将name 换为 value
          if (response.rows) {
            response.rows.forEach(item => {
              item.value = item.name;
            });
            cb(response.rows);
            this.driverList = response.rows;
          }
        });
      }
    },
    /** 司机名称选中 */
    handleDriverSelect(item) {
      this.shipmentForm.outDriver = item.name;
      this.shipmentForm.jcDriverId = item.id;
      this.shipmentForm.outPhone = item.iphone1;
    },
    getOrgList() {
      this.orgList = []
      orgTree().then(response => {
        if (response.data) {
          this.orgList = response.data
        }
      })
    },
    changeOrg(value) {
      this.viaOrgIds = []
      // 从 orgList 中删除 jcFromOrganizationId、jcToOrganizationId
      this.viaOrgIds = this.orgList.filter(item => item.id !== this.shipmentForm.jcFromOrganizationId && item.id !== this.shipmentForm.jcToOrganizationId)
    },
    getFeeTypeData() {
      this.feeTypeData = []
      listFeeTypeOption('2.1').then(response => {
        if (response.data) {
          this.feeTypeData = response.data
        }
      })
    },
    changeFeeType(row, item) {
      row.name = item.name
      row.jcFeeTypeCode = item.code
    },
    changeAmount(row) {
      row.input = row.amount * row.taxrate
      row.income = row.amount - row.input
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.shipmentForm = {
        id: null,
        code: null,
        createName: null,
        createTime: null,
        description: null,
        modifyName: null,
        modifyTime: null,
        name: null,
        status: null,
        backNumber: null,
        carriageIsExceed: null,
        carrierType: null,
        factArriveTime: null,
        factLeaverTime: null,
        feeType: null,
        isAbnormal: null,
        license: null,
        number: null,
        operationPattern: null,
        orderCode: null,
        outDriver: null,
        planLeaveTime: null,
        refuse: null,
        relateBill1: null,
        requireArriveTime: null,
        shipmentMethod: null,
        tan: null,
        time: new Date(),
        value: null,
        volume: null,
        weight: null,
        jcCarrierId: null,
        jcDriverId: null,
        jcOrganizationId: null,
        jcSettlementId: null,
        jcVehicleId: null,
        jcVehicleHeadId: null,
        actionTime: null,
        jcFromOrganizationId: null,
        jcNowOrganizationId: null,
        jcNextOrganizationId: null,
        jcToOrganizationId: null,
        orgIds: null,
        orgIdsArray: null,
        outPhone: null,
        orgnameList: null,
        jzWeight: null,
        isConfirm: null
      };
      this.ledgerDetails = [];
      this.resetForm("shipmentForm");
    },
    /** 台帐明细序号 */
    rowJcLedgerDetailIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 台帐明细添加按钮操作 */
    handleAddJcLedgerDetail() {
      let obj = {};
      obj.createName = "";
      obj.description = "";
      obj.field1 = "";
      obj.modifyName = "";
      obj.modifyTime = "";
      obj.name = "";
      obj.status = "";
      obj.amount = "";
      obj.explain1 = "";
      obj.explain2 = "";
      obj.explain3 = "";
      obj.input = "";
      obj.occurrenceTime = "";
      obj.taxrate = "0.09";
      obj.jcFeeTypeId = "";
      obj.jcLedgerId = "";
      obj.cost = "";
      obj.type = "";
      obj.jcOrderId = "";
      obj.jcPrescoId = "";
      obj.jcDispatchId = "";
      obj.jcFeeSeedId = "";
      obj.jcOtherfeeId = "";
      obj.arrivePay = "";
      obj.backPay = "";
      obj.hxmoney = "";
      obj.montyPay = "";
      obj.nowPay = "";
      obj.whmoney = "";
      obj.cashAdvances = "";
      obj.oilPrepaid = "";
      obj.yuE = "";
      obj.zFy = "";
      obj.zGxyf = "";
      obj.zQtfy = "";
      obj.zShf = "";
      obj.zThf = "";
      obj.yajin = "";
      obj.yfYouka = "";
      obj.income = "";
      obj.outcome = "";
      obj.jcShipmentTemplateId = "";
      obj.jcCarrierId = "";
      obj.affirmTime = "";
      obj.isConfirm = "";
      obj.collectMethod = "";
      obj.payMethod = "";
      obj.settlementMethod = "";
      this.ledgerDetails.push(obj);
    },
    /** 台帐明细删除按钮操作 */
    handleDeleteJcLedgerDetail() {
      if (this.checkedJcLedgerDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的台帐明细数据");
      } else {
        const ledgerDetails = this.ledgerDetails;
        const checkedJcLedgerDetail = this.checkedJcLedgerDetail;
        this.ledgerDetails = ledgerDetails.filter(function (item) {
          return checkedJcLedgerDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleJcLedgerDetailSelectionChange(selection) {
      this.checkedJcLedgerDetail = selection.map(item => item.index)
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      this.open = true;
      getShipment(id).then(response => {
        this.shipmentForm = response.data;
        if (response.data.orgIds) {
          this.shipmentForm.orgIdsArray = response.data.orgIds.split(',');
        }
        this.changeOrg();
        if (response.data.ledgerDetails) {
          this.ledgerDetails = response.data.ledgerDetails;
        }
        this.title = "修改运单异常信息";
      });
    },
    /** 提交按钮 */
    submitShipmentFormForm() {
      this.$refs["shipmentForm"].validate(valid => {
        if (valid) {
          this.shipmentForm.ledgerDetails = this.ledgerDetails;
          if (this.shipmentForm.orgIdsArray) {
            this.shipmentForm.orgIds = this.shipmentForm.orgIdsArray.join(",");
          }
          const data = {
            jcShipment: this.shipmentForm,
            abnormal: this.shipmentForm.abnormal
          }
          saveAbnormalShipment(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.reset();
            this.open = false;
            this.$emit('change');
          });
        }
      });
    },
  }
};
</script>
<style scoped>
.el-form-item {
  margin-bottom: 15px;
}
</style>
